/**
 *  双组织组合选择，目前仅考虑考勤管理的场景
 */
import { connect } from 'umi';
import React from 'react';
import { withRouter } from 'umi';
import Company from './Company';
import Organization from './Organization';

const getDefaultValue = (query, user, key) => {
    if (query[`${key}Id`] === '' || query[`${key}Code`] === '') {
        return undefined;
    }
    return query[`${key}Id`] || query[`${key}Code`] || user[`${key}Id`];
};

const CompanyDepart = props => {
    const { value = {}, onChange, style, hideCompany = false, hideOrg = false, user, location, requestParams } = props;
    const { query } = location;
    const { companyId, departmentId } = value;
    const handleChange = _value => {
        onChange({ ...value, ..._value });
    };

    // 默认值，兼容不同写法。
    React.useEffect(() => {
        onChange({
            companyId: hideCompany ? undefined : getDefaultValue(query, user, 'company'),
            departmentId: hideOrg ? undefined : getDefaultValue(query, user, 'department')
        });
    }, []);

    const isSingle = hideCompany || hideOrg;

    return (
        <div style={{ height: 40, display: 'flex', alignItems: 'center', ...style }}>
            {!hideCompany && (
                <Company
                    value={companyId}
                    style={{ marginRight: isSingle ? 0 : 8, maxWidth: 170 }}
                    onChange={_value => {
                        handleChange({
                            companyId: _value
                        });
                    }}
                    requestParams={requestParams}
                />
            )}
            {!hideOrg && (
                <Organization
                    value={departmentId}
                    style={{ maxWidth: 170 }}
                    onChange={_value => {
                        handleChange({
                            departmentId: _value
                        });
                    }}
                />
            )}
        </div>
    );
};

const WrapComponent = connect(({ user }) => ({ user: user.currentUser }))(withRouter(CompanyDepart));

export default React.forwardRef((props, ref) => <WrapComponent {...props} refInstance={ref} />);
